<template>
  <div>
    <div style="margin-bottom: 10px;">
      <el-select v-model="searchName" filterable placeholder="请输入班级名称" clearable
        style="width: 200px; margin-right: 10px;">
        <el-option v-for="option in employmentNameOptions" :key="option" :label="option"
          :value="option" />
      </el-select>
      <el-select filterable v-model="searchStatus" placeholder="请输入就业状态" clearable
        style="width: 200px; margin-right: 10px;">
        <el-option v-for="option in employmentStatusOptions" :key="option.value" :label="option.value"
          :value="option.value" />
      </el-select>
      <el-button type="primary" @click="list()">查询</el-button>
      <el-button type="success" @click="handleAddSubmit" style="margin-left: 10px;">批量上传</el-button>
      <el-upload :action="uploadUrl" :on-success="handleUploadSuccess" :on-error="handleUploadError"
        style="display: inline-block; margin-left: 10px;" :before-upload="beforeUpload" :show-file-list="false"
        accept=".xlsx, .xls">
        <el-button type="success">批量导入</el-button>
      </el-upload>



    </div>

    <el-dialog v-model="showAddForm" title="添加班级信息" width="80%">
      <div>
        <div>
          <el-button size="small" @click="addRow">新增</el-button>
        </div>
        <!--设置的表单-->
        <el-form :model="studentData" ref="data" label-width="auto">
          <el-table border :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
            :data="studentData" ref="table" style="width: 100%">

            <el-table-column align="center" label="班级名称">
              <template #default="scope">
                <!--表格里面嵌套表单-->
                <el-form-item :prop="scope.$index + '.clazzName'"
                  :rules="{ required: true, message: '班级名称不能为空', trigger: 'blur' }">
                  <el-input v-model="studentData[scope.$index].clazzName" autocomplete="off" size="small"
                    placeholder="班级名称"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="就业开始时间">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzStart'"
                  :rules="{ required: true, message: '就业开始时间不能为空', trigger: 'blur' }">

                  <el-date-picker v-model="studentData[scope.$index].clazzStart" size="small" type="date"
                    format="YYYY-MM-DD" placeholder="就业开始时间" value-format="YYYY-MM-DD" />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="就业天数">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzDays'"
                  :rules="{ required: true, message: '就业天数不能为空', trigger: 'blur' }">
                  <el-input v-model="studentData[scope.$index].clazzDays" autocomplete="off" size="small"
                    placeholder="就业天数"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="项目经理">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzManager'"
                  :rules="{ required: true, message: '项目经理不能为空', trigger: 'blur' }">
                  <el-input v-model="studentData[scope.$index].clazzManager" autocomplete="off" size="small"
                    placeholder="项目经理"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="班主任">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzTeacher'"
                  :rules="{ required: true, message: '班主任不能为空', trigger: 'blur' }">
                  <el-input v-model="studentData[scope.$index].clazzTeacher" autocomplete="off" size="small"
                    placeholder="班主任"></el-input>
                </el-form-item>
              </template>
            </el-table-column>


            <el-table-column align="center" label="推迟原因">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzReason'"
                  :rules="{ validator: validateClazzReason, trigger: 'blur' }">
                  <el-input v-model="studentData[scope.$index].clazzReason" autocomplete="off" size="small"
                    placeholder="推迟原因"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="就业状态">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.clazzStatus'"
                  :rules="{ required: true, message: '就业状态不能为空', trigger: 'blur' }">

                  <el-select v-model="studentData[scope.$index].clazzStatus" size="small" placeholder="请选择就业状态">
                    <el-option v-for="item in employStatus" :key="item.sta" :value="item.sta">
                      {{ item.sta }}
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column align="center" label="方向">
              <template #default="scope">
                <el-form-item :prop="scope.$index + '.majorName'"
                  :rules="{ required: true, message: '方向不能为空', trigger: 'blur' }">
                  <el-select v-model="studentData[scope.$index].majorName" size="small" placeholder="请选择方向">
                    <el-option v-for="item in options" :key="item.majorId" :value="item.majorName">
                      {{ item.majorName }}
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>




            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button @click="handleDeleteRow(studentData[scope.$index])" type="text" size="small">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer" style="margin-bottom: 10px">
        <el-button size="small" @click="submit">提交</el-button>
        <el-button size="small" @click="resetForm()">重置</el-button>
      </div>


    </el-dialog>

    <el-dialog v-model="addClazzDays" title="上传推迟就业天数原因" width="50%">
      <el-form :model="updateReason" ref="ruleFormRef">
        <el-form-item label="推迟天数" prop="days" :rules="{ required: true, message: '推迟天数不能为空', trigger: 'blur' }">
          <el-input v-model="updateReason.days" type="number"></el-input>
        </el-form-item>
        <el-form-item label="推迟原因" prop="reason" :rules="{ required: true, message: '推迟原因不能为空', trigger: 'blur' }">
          <el-input v-model="updateReason.reason"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClazzDays = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </span>

    </el-dialog>



<!-- 数据表格 -->
<el-table :data="tableData" border style="width: 100%" :row-class-name="tableRowClassName">
  <el-table-column prop="clazzId" label="班级编号" width="60" />
  <el-table-column prop="clazzName" label="班级名称" width="100" />
  <el-table-column prop="realStudent" label="班级人数" width="100" />
  <el-table-column prop="clazzStart" label="就业开始时间" />
  <el-table-column prop="clazzEnd" label="就业结束时间" />
  <el-table-column prop="clazzManager" label="项目经理" />
  <el-table-column prop="clazzTeacher" label="班主任" />
  <el-table-column prop="clazzStatus" label="就业状态" />
  <el-table-column prop="clazzDays" v-if="false"/>
  <el-table-column prop="unemployedCount" label="未就业人数" width="60">
    <template #default="scope">
      <a @click="getNoEmployment(scope.row.clazzName)" target="_blank" class="unemployed-count" style="text-decoration: none;">{{
        scope.row.unemployedCount }}</a>
    </template>
  </el-table-column>
  <el-table-column prop="employmentRate" label="就业率" :formatter="formatEmploymentRate">
    <template #default="scope">
      <a @click="getEmployment(scope.row.clazzName)"
        :class="{ 'shadow-effect': isActiveRow(scope.row), 'employment-rate': true }" style="text-decoration: none;">{{
          formatEmploymentRate(scope.row.employmentRate) }}</a>
    </template>
  </el-table-column>

  <!-- 编辑按钮 -->
  <el-table-column label="操作" width="150">
    <template #default="scope">
      <el-button type="primary" @click="handleEdit(scope.row)">推迟就业天数</el-button>
    </template>
  </el-table-column>
</el-table>

    <!-- 分页 -->
    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
        :size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElButton, ElTable, ElTableColumn, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { rateClazzApi } from '@/api/clazz-api';
import { addClazzApi } from '@/api/clazz-api';
import { getMajorApi } from '@/api/clazz-api';
import { uploadApi } from '@/api/clazz-api';
import { GetClazzNameApi } from '@/api/clazz-api';
import { updateClazzApi } from '@/api/clazz-api';
import router from '@/router';
import {  ElUpload, ElTag, ElDescriptions, ElDescriptionsItem } from 'element-plus';
import { error } from 'console';
let employmentNameOptions :any=ref([])
const updateEmploymentNameOptions = async () => {
  const response = await GetClazzNameApi();
  if (response.code === 200) {
    employmentNameOptions.value = response.data; 
  } else {
  }
};
const employmentStatusOptions = [
  { value: '未完成', label: '未完成' },
  { value: '完成', label: '完成' },
  { value: '未开始', label: '未开始' },
  { value: '结束', label: '结束' },

];


//分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(10)
const size = ref('default')

// 搜索条件  
const searchName = ref('');
const searchStatus = ref('');

// 表格数据  
const tableData = ref([]);

const employStatus = ref([{ sta: '未完成' }, { sta: '完成' }, { sta: '未开始' }, { sta: '结束' }])

// 弹窗
const showAddForm = ref(false);
const addClazzDays = ref(false);
const updateReason = ref({
  clazzId: 1,
  days: 0,
  reason: '',
})

const options = ref([{

  majorId: 1,
  majorName: '',

}])

const studentData = ref([{
  key: 1,
  clazzName: '',
  clazzStart: '',
  clazzManager: '',
  clazzTeacher: '',
  clazzStatus: '',
  clazzDays: '',
  majorName: '',
  clazzReason: '',
  
}]);

// 上传 URL
const uploadUrl = ref('/clazz/upload');

// 文件上传成功回调
const handleUploadSuccess = (response: any, file: File, fileList: File[]) => {

  if (response.code === 200) {
    ElMessage.success('导入成功');
    list(); // 刷新表格数据
  } else {
    ElMessage.error(response.message || '导入失败');
  }
  return undefined;
};

// 文件上传失败回调
const handleUploadError = (err: Error, file: File, fileList: File[]) => {
  err
  file
  fileList
  ElMessage.error('文件上传失败，请稍后再试');
  return undefined;
};

// 上传前校验文件格式
const beforeUpload = async (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel';
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件');
    return false;
  }

  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await uploadApi(formData);
    console.log('上传前校验文件格式', response);
    if (response.code === 200) {
      ElMessage.success('导入成功');
      await list(); // 刷新表格数据
    } else {
      ElMessage.error(response.msg || '导入失败');
    }
  } catch (error) {
    ElMessage.error('文件上传失败，请稍后再试');
  }

  return false; // 阻止默认上传行为
};

const ruleFormRef = ref();
const validateClazzReason=(rule: any, value: string, callback:any) =>{
  const index = rule.field.split('.')[0];
  const clazzDays = studentData.value[index] && Number(studentData.value[index].clazzDays);

  // 检查 clazzDays 是否为有效的数字
  if (isNaN(clazzDays)) {
    console.error(`Invalid clazzDays value for index ${index}: ${studentData.value[index].clazzDays}`);
    return callback(new Error('就业天数无效'));
  }

    if (clazzDays > 90 && (!value || value.trim() === '') ) {
      callback(new Error('推迟原因为必填项'));
    } else {
      callback();
    }
  }

const getNoEmployment = (clazzName: any) => {
  const noEmployment = {
    clazzStatus: '未就业',
    clazzName: clazzName,
  }

  localStorage.setItem("employmentJson", JSON.stringify(noEmployment));
  router.push('/clazz/clazzStudent')
  .0

}
const activeRow=ref(null)
const isActiveRow=(row: any)=> {
      // 检查当前行是否为激活状态
      return activeRow === row;
}
const getEmployment = (clazzName: any) => {
  activeRow.value = clazzName;
  const Employment = {
    clazzStatus: '已就业',
    clazzName: clazzName,
  }

  localStorage.setItem("employmentJson", JSON.stringify(Employment));
  router.push('/clazz/clazzStudent')
}

// 编辑功能  
const handleEdit = (row: any) => {
  updateReason.value = {
    clazzId: 0,
    days: 0,
    reason: '',
  }

  addClazzDays.value = true;
  updateReason.value.clazzId = row.clazzId;
  updateReason.value.days=row.clazzDays;

};


const update = () => {
  ruleFormRef.value.validate(async (valid: any) => {


    if (valid) {
      //如果验证通过，这调用登录方法


      try {
        console.log(updateReason.value)
        const response = await updateClazzApi(updateReason.value);
        console.log('登录响应数据', response);
        if (response.code === 200) {
          ElMessage.info('修改成功');
          addClazzDays.value = false;
          list();

        } else {
          ElMessage.error(response.msg);
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后再试');
      }
    } else {
      ElMessage({
        message: '数据格式有误',
        type: 'error',
        duration: 1000, // 消息提示框显示的时间，单位是毫秒
      });
    }
  })

}


// 查询列表  
const list = async () => {
  const response = await rateClazzApi({ clazzName: searchName.value, clazzStatus: searchStatus.value, page: currentPage.value, size: pageSize.value });
  if (response.code === 200) {
    tableData.value = response.data.list;

    total.value = response.data.total;
  } else {
    ElMessage.error(response.msg);
  }
};


const formatEmploymentRate = (rate: any) => {
  if (!rate) return '';
  return `${(rate * 100).toFixed(0)}%`;
}


// 格式化时间的方法  去掉T
const formatTime = (time: string) => {
  if (!time) return '';
  return time.replace('T', ' ');
}


// 新增功能  
const handleAddSubmit = async () => {
  studentData.value = [];
  getMajoir();
  showAddForm.value = true;
};

const addRow = () => {

  const index = studentData.value.length;
  getMajoir();
  studentData.value.push({
    key: index,
    clazzName: '',
    clazzStart: '',
    clazzManager: '',
    clazzTeacher: '',
    clazzStatus: '',
    clazzDays: '',
    majorName: '',
    clazzReason: '',
  });
},

  /**
   * 删除行
   * @param row
   */
  handleDeleteRow = (row: any) => {
    const datas = studentData.value;

    for (var i = 0; i < datas.length; i++) {
      if (datas[i].key == row.key) {
        datas.splice(i, 1);
      }
    }
  };

async function handleLogin() {
  try {
    const response = await addClazzApi(studentData.value);
    console.log('登录响应数据', response);
    if (response.code === 200) {

      studentData.value = [];
      showAddForm.value = false;

    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后再试');
  }
}

async function getMajoir() {
  try {
    const response = await getMajorApi();
    console.log('登录响应数据', response);
    if (response.code === 200) {
      options.value = response.data

    } else {
      ElMessage.error(response.msg);
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后再试');
  }
}


const data = ref();

//提交数据
const submit = () => {
  data.value.validate((valid: any) => {


    if (valid) {
      //如果验证通过，这调用登录方法
      handleLogin()
    } else {
      ElMessage({
        message: '数据格式有误',
        type: 'error',
        duration: 1000, // 消息提示框显示的时间，单位是毫秒
      });
    }
  })
}

/**
 * 重置
 */
const resetForm = () => {
  let datas = studentData.value;
  for (var i = 0; i < datas.length; i++) {
    datas[i].clazzStart = '';

    datas[i].clazzStart = '';
    datas[i].clazzManager = '';
    datas[i].clazzTeacher = '';
    datas[i].clazzStatus = '';
    datas[i].clazzDays = '';
  }
};





// 处理每页显示条数变化的事件  
const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  list();
};

// 处理当前页码变化的事件  
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  list();
};

// 删除
const handleDelete = async (id: number) => {
  ElMessageBox.confirm(
    '确认删除?',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {

  }).catch(() => {
    ElMessage.info('已取消');
  });
}

// 页面加载完后，加载默认数据  
onMounted(() => {
  updateEmploymentNameOptions();
  list();
});  

// 表格行样式
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  row
  if (rowIndex % 2 === 0) {
    return 'success-row'
  }
  return ''
}
</script>
<style scoped>
.shadow-effect {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: box-shadow 0.3s;
}

.unemployed-count {
  color: rgb(0, 204, 255); /* 默认颜色为蓝色 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
  text-decoration: underline; /* 添加下划线 */
}

.unemployed-count:hover {
  color: darkblue; /* 鼠标悬停时颜色变为深蓝色 */
}

.employment-rate {
  color: rgb(0, 204, 255); /* 默认颜色为蓝色 */
  cursor: pointer; /* 鼠标悬停时显示为指针 */
  text-decoration: underline; /* 添加下划线 */
}

.employment-rate:hover {
  color: darkblue; /* 鼠标悬停时颜色变为深蓝色 */
}

  
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>